﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team - cellcloudproject@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "CellStableHeaders.h"
#include "CellPerformance.h"
#include "CellLoggerManager.h"

#if CELL_COMPILER == CELL_COMPILER_MSVC
	#include <WinSock2.h>
	#include <Ws2tcpip.h>
	#include <Windows.h>
	#include <Psapi.h>
	#include <ctime>
	#if _MSC_VER >= 1400
		#include <intrin.h>
	#endif
#elif CELL_COMPILER == CELL_COMPILER_GNUC
	#include <signal.h>
	#include <setjmp.h>

	#if CELL_CPU == CELL_CPU_ARM
		#include <sys/sysctl.h>
		#include <mach/machine.h>
	#endif
#endif

namespace cell
{

#if CELL_PLATFORM == CELL_PLATFORM_WIN32
/// 时间转换
static uint64 file_time_2_utc(const FILETIME* ftime)
{
	LARGE_INTEGER li;

	li.LowPart = ftime->dwLowDateTime;
	li.HighPart = ftime->dwHighDateTime;
	return li.QuadPart;
}
#endif

#define CPU_USAGE_LISTLENGTH 10

//-----------------------------------------------------------------------
Performance::Performance(void)
	: mSpinning(false)
	, mRunning(false)
	, mNumberOfProcessors(0)
	, mProcessId(0)
	, mLastTime(0)
	, mLastSystemTime(0)
	, mTotalVirtualMem(0)
	, mVirtualMemUsed(0)
	, mTotalPhysicalMem(0)
	, mPhysicalMemUsed(0)
	, mProcessVirtualMemUsed(0)
	, mProcessPhysicalMemUsed(0)
{
	mNumberOfProcessors = getProcessorNumber();
	mProcessId = getCurrentProcessId();
}
//-----------------------------------------------------------------------
Performance::~Performance(void)
{
}
//-----------------------------------------------------------------------
void Performance::run(void)
{
	mRunning = true;

	collectHostInfo(mHostName, mIPAddressList);

	int collectTimeCount = 60;

	mSpinning = true;
	while (mSpinning)
	{
		if (collectTimeCount == 60)
		{
			collectInfo();

			collectTimeCount = 0;
		}

		++collectTimeCount;

		Thread::sleep(1000);
	}

	mRunning = false;
}
//-----------------------------------------------------------------------
void Performance::stop(void)
{
	LoggerManager::getSingleton().log("Stop performace thread...");

	mSpinning = false;
}
//-----------------------------------------------------------------------
void Performance::await(void)
{
	while (mRunning)
	{
		Thread::sleep(10);
	}
}
//-----------------------------------------------------------------------
inline const String& Performance::getHostName(void) const
{
	return mHostName;
}
//-----------------------------------------------------------------------
inline const StringVector& Performance::getIPAddressList(void) const
{
	return mIPAddressList;
}
//-----------------------------------------------------------------------
ulong Performance::getCurrentProcessId(void) const
{
#if CELL_PLATFORM == CELL_PLATFORM_WIN32
	return ::GetCurrentProcessId();
#else
	// TODO
	return 0;
#endif
}
//-----------------------------------------------------------------------
int Performance::getProcessorNumber(void) const
{
#if CELL_PLATFORM == CELL_PLATFORM_WIN32
	SYSTEM_INFO info;
	GetSystemInfo(&info);
	return (int)info.dwNumberOfProcessors;
#else
	// TODO
	return 0;
#endif
}
//-----------------------------------------------------------------------
uint64 Performance::getTotalVirtualMemory(void) const
{
	return mTotalVirtualMem;
}
//-----------------------------------------------------------------------
uint64 Performance::getVirtualMemoryUsed(void) const
{
	return mVirtualMemUsed;
}
//-----------------------------------------------------------------------
uint64 Performance::getTotalPhysicalMemory(void) const
{
	return mTotalPhysicalMem;
}
//-----------------------------------------------------------------------
uint64 Performance::getPhysicalMemoryUsed(void) const
{
	return mPhysicalMemUsed;
}
//-----------------------------------------------------------------------
inline int Performance::getProcessCPUUsage(void) const
{
	if (mCPUUsageList.empty())
		return 0;

	return mCPUUsageList.back();
}
//-----------------------------------------------------------------------
inline uint64 Performance::getProcessVirtualMemoryUsed(void) const
{
	return mProcessVirtualMemUsed;
}
//-----------------------------------------------------------------------
inline uint64 Performance::getProcessPhysicalMemoryUsed(void) const
{
	return mProcessPhysicalMemUsed;
}
//-----------------------------------------------------------------------
void Performance::collectInfo(void)
{
#if CELL_PLATFORM == CELL_PLATFORM_WIN32
	// 内存基本信息
	MEMORYSTATUSEX memInfo;
	memInfo.dwLength = sizeof(MEMORYSTATUSEX);
	GlobalMemoryStatusEx(&memInfo);
	mTotalVirtualMem = memInfo.ullTotalPageFile;
	mVirtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
	mTotalPhysicalMem = memInfo.ullTotalPhys;
	mPhysicalMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;

	//OpenProcess(PROCESS_ALL_ACCESS, false, mProcessId);
	HANDLE hProcess = GetCurrentProcess();
	if (NULL == hProcess)
	{
		return;
	}

	PROCESS_MEMORY_COUNTERS_EX pmc;
	GetProcessMemoryInfo(hProcess, (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
	mProcessVirtualMemUsed = pmc.PrivateUsage;
	mProcessPhysicalMemUsed = pmc.WorkingSetSize;

	FILETIME now;
	FILETIME creationTime;
	FILETIME exitTime;
	FILETIME kernelTime;
	FILETIME userTime;
	uint64 systemTime;
	uint64 time;
	uint64 systemTimeDelta;
	uint64 timeDelta;

	GetSystemTimeAsFileTime(&now);

	if (!GetProcessTimes(hProcess, &creationTime, &exitTime, &kernelTime, &userTime))
	{
		CloseHandle(hProcess);
		return;
	}

	CloseHandle(hProcess);

	systemTime = (file_time_2_utc(&kernelTime) + file_time_2_utc(&userTime)) / mNumberOfProcessors;
	time = file_time_2_utc(&now);

	if ((mLastSystemTime == 0) || (mLastTime == 0))
	{
		mLastSystemTime = systemTime;
		mLastTime = time;
		collectInfo();
		return;
	}

	systemTimeDelta = systemTime - mLastSystemTime;
	timeDelta = time - mLastTime;

	if (timeDelta == 0)
		return;

	int usage = (int)((systemTimeDelta * 100) / timeDelta);
	mLastSystemTime = systemTime;
	mLastTime = time;

	if (mCPUUsageList.size() >= CPU_USAGE_LISTLENGTH)
	{
		mCPUUsageList.pop_front();
	}
	mCPUUsageList.push_back(usage);
#else
	// TODO
#endif
}
//-----------------------------------------------------------------------
bool Performance::collectHostInfo(String& hostName, StringVector& addressList)
{
	char szHostName[256] = {0x0};
	if (SOCKET_ERROR == ::gethostname(szHostName, sizeof(szHostName)))
		return false;

	hostName = szHostName;

	struct hostent *phe = ::gethostbyname(szHostName);
	if (phe == NULL)
	{
		return false;
	}

	char **pptr;
	switch (phe->h_addrtype)
	{
	case AF_INET:
	case AF_INET6:
		for (pptr = phe->h_addr_list; *pptr != NULL; pptr++)
		{
			char str[64] = {0x0};
			inet_ntop(phe->h_addrtype, *pptr, str, sizeof(str));
			addressList.push_back(str);
		}
		break;
	default:
		break;
	}

	return true;
}

} // end namespace cell
